package com.cy.sdk.qiniu;


import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.rs.PutPolicy;
import com.cy.config.Config;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-11-27
 * Time: 上午9:48
 * To change this template use File | Settings | File Templates.
 */
public class QiniuToken {

    public static String getUploadToken(String bucketName) throws Exception {
        return  getUploadToken(null, bucketName);
    }
    public static String getUploadToken(String code, String bucketName) throws Exception {
        return getUploadToken(code, bucketName, null, null, null, null, null);
    }


    public static String getLongTimeUploadToken(String code, String bucketName) throws Exception {
        return getUploadToken(code, bucketName, Long.valueOf(3600000), null, null, null, null);
    }

    /**
     * 获取七牛上传的token
     *
     * @param expires      过期时间 单位 s
     * @param callbackUrl  回调的URL
     * @param callbackBody 回调的函数
     * @param returnUrl    返回的URL
     * @param returnBody   返回的函数
     * @return
     * @throws AuthException
     * @throws JSONException
     */
    public static String getUploadToken(String code, String bucketName, Long expires, String callbackUrl, String callbackBody, String returnUrl, String returnBody) throws Exception {
        Mac mac = new Mac(Config.QiNiu.ACCESS_KEY, Config.QiNiu.SECRET_KEY);
        if (StringUtils.isBlank(bucketName)) {
            throw new Exception("no bucketName");
        }

        PutPolicy putPolicy = new PutPolicy(bucketName);

        putPolicy.callbackBody = callbackBody;
        putPolicy.callbackUrl = callbackUrl;
        if (StringUtils.isNotBlank(code)) {
            putPolicy.saveKey = code + "/$(etag)";
        }


        if (StringUtils.isBlank(returnBody)) {
            returnBody = "  {\n" +
                    "    \"status\": \"1\",\n" +
                    "    \"name\": $(fname),\n" +
                    "    \"bucketName\": \"" + bucketName + "\",\n" +
                    "    \"url\": $(key),\n" +
                    "    \"size\": $(fsize),\n" +
                    "    \"type\": $(mimeType),\n" +
                    "    \"hash\": $(etag),\n" +
                    "    \"w\": $(imageInfo.width),\n" +
                    "    \"h\": $(imageInfo.height)\n" +
                    "  }";
        }

        putPolicy.returnBody = returnBody;
        putPolicy.returnUrl = returnUrl;
        if (expires != null) {
            putPolicy.expires = expires;
        }

        String uptoken = putPolicy.token(mac);
        return uptoken;
    }
}
